<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
<meta name="generator" content="Hexo 5.4.0">


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png">
  <link rel="mask-icon" href="/images/logo.svg" color="#222">

<link rel="stylesheet" href="/css/main.css">



<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free@5.15.2/css/all.min.css">
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/animate.css@3.1.1/animate.min.css">

<script class="hexo-configurations">
    var NexT = window.NexT || {};
    var CONFIG = {"hostname":"littlefxc.github.io","root":"/","images":"/images","scheme":"Mist","version":"8.2.2","exturl":false,"sidebar":{"position":"left","display":"post","padding":18,"offset":12},"copycode":false,"bookmark":{"enable":false,"color":"#222","save":"auto"},"fancybox":false,"mediumzoom":false,"lazyload":false,"pangu":false,"comments":{"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},"motion":{"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"fadeInDown","post_body":"fadeInDown","coll_header":"fadeInLeft","sidebar":"fadeInUp"}},"prism":false,"i18n":{"placeholder":"搜索...","empty":"没有找到任何搜索结果：${query}","hits_time":"找到 ${hits} 个搜索结果（用时 ${time} 毫秒）","hits":"找到 ${hits} 个搜索结果"},"path":"/search.xml","localsearch":{"enable":true,"trigger":"auto","top_n_per_article":1,"unescape":false,"preload":false}};
  </script>
<meta name="description" content="[toc] 引言简单来说，回表就是 MySQL 要先查询到主键索引，然后再用主键索引定位到数据。 下面，对一些问题进行分析与回答：  什么是聚簇索引？什么是非聚簇索引？ 为什么回表要先查到主键索引？ 主键索引和非主键索引有什么区别？ 如何避免回表？  聚簇索引和非聚簇索引是什么？MySQL 的索引有不同的角度的分类方式，例如：按数据结构分、按逻辑角度分、按物理存储分。 其中，按物理存储分有两种索引">
<meta property="og:type" content="article">
<meta property="og:title" content="什么是MySQL的回表?">
<meta property="og:url" content="http://littlefxc.github.io/2022/03/18/docs/MySQL/%E4%BB%80%E4%B9%88%E6%98%AFMySQL%E7%9A%84%E5%9B%9E%E8%A1%A8/index.html">
<meta property="og:site_name" content="一年春又来">
<meta property="og:description" content="[toc] 引言简单来说，回表就是 MySQL 要先查询到主键索引，然后再用主键索引定位到数据。 下面，对一些问题进行分析与回答：  什么是聚簇索引？什么是非聚簇索引？ 为什么回表要先查到主键索引？ 主键索引和非主键索引有什么区别？ 如何避免回表？  聚簇索引和非聚簇索引是什么？MySQL 的索引有不同的角度的分类方式，例如：按数据结构分、按逻辑角度分、按物理存储分。 其中，按物理存储分有两种索引">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://gitee.com/littlefxc/oss/raw/master/images/8ec43769f81ea5e901077f047b8da974.png">
<meta property="article:published_time" content="2022-03-17T18:41:19.000Z">
<meta property="article:modified_time" content="2022-05-10T01:23:09.233Z">
<meta property="article:author" content="一年春又来">
<meta property="article:tag" content="mysql">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://gitee.com/littlefxc/oss/raw/master/images/8ec43769f81ea5e901077f047b8da974.png">


<link rel="canonical" href="http://littlefxc.github.io/2022/03/18/docs/MySQL/%E4%BB%80%E4%B9%88%E6%98%AFMySQL%E7%9A%84%E5%9B%9E%E8%A1%A8/">


<script class="page-configurations">
  // https://hexo.io/docs/variables.html
  CONFIG.page = {
    sidebar: "",
    isHome : false,
    isPost : true,
    lang   : 'zh-CN'
  };
</script>
<title>什么是MySQL的回表? | 一年春又来</title>
  




  <noscript>
  <style>
  body { margin-top: 2rem; }

  .use-motion .menu-item,
  .use-motion .sidebar,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-header {
    visibility: visible;
  }

  .use-motion .header,
  .use-motion .site-brand-container .toggle,
  .use-motion .footer { opacity: initial; }

  .use-motion .site-title,
  .use-motion .site-subtitle,
  .use-motion .custom-logo-image {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line {
    transform: scaleX(1);
  }

  .search-pop-overlay, .sidebar-nav { display: none; }
  .sidebar-panel { display: block; }
  </style>
</noscript>

<link rel="alternate" href="/atom.xml" title="一年春又来" type="application/atom+xml">
</head>

<body itemscope itemtype="http://schema.org/WebPage" class="use-motion">
  <div class="headband"></div>

  <main class="main">
    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏" role="button">
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/" class="brand" rel="start">
      <i class="logo-line"></i>
      <h1 class="site-title">一年春又来</h1>
      <i class="logo-line"></i>
    </a>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger">
        <i class="fa fa-search fa-fw fa-lg"></i>
    </div>
  </div>
</div>



<nav class="site-nav">
  <ul class="main-menu menu">
        <li class="menu-item menu-item-home"><a href="/" rel="section"><i class="home                          //首页 fa-fw"></i>首页</a></li>
        <li class="menu-item menu-item-archives"><a href="/archives/" rel="section"><i class="archive          //归档 fa-fw"></i>归档</a></li>
        <li class="menu-item menu-item-categories"><a href="/categories/" rel="section"><i class="th           //分类 fa-fw"></i>分类</a></li>
        <li class="menu-item menu-item-tags"><a href="/tags/" rel="section"><i class="tags                     //标签 fa-fw"></i>标签</a></li>
      <li class="menu-item menu-item-search">
        <a role="button" class="popup-trigger"><i class="fa fa-search fa-fw"></i>搜索
        </a>
      </li>
  </ul>
</nav>



  <div class="search-pop-overlay">
    <div class="popup search-popup"><div class="search-header">
  <span class="search-icon">
    <i class="fa fa-search"></i>
  </span>
  <div class="search-input-container">
    <input autocomplete="off" autocapitalize="off" maxlength="80"
           placeholder="搜索..." spellcheck="false"
           type="search" class="search-input">
  </div>
  <span class="popup-btn-close" role="button">
    <i class="fa fa-times-circle"></i>
  </span>
</div>
<div class="search-result-container no-result">
  <div class="search-result-icon">
    <i class="fa fa-spinner fa-pulse fa-5x"></i>
  </div>
</div>

    </div>
  </div>

</div>
        
  
  <div class="toggle sidebar-toggle" role="button">
    <span class="toggle-line"></span>
    <span class="toggle-line"></span>
    <span class="toggle-line"></span>
  </div>

  <aside class="sidebar">

    <div class="sidebar-inner sidebar-nav-active sidebar-toc-active">
      <ul class="sidebar-nav">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <div class="sidebar-panel-container">
        <!--noindex-->
        <div class="post-toc-wrap sidebar-panel">
            <div class="post-toc animated"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#%E5%BC%95%E8%A8%80"><span class="nav-text">引言</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#%E8%81%9A%E7%B0%87%E7%B4%A2%E5%BC%95%E5%92%8C%E9%9D%9E%E8%81%9A%E7%B0%87%E7%B4%A2%E5%BC%95%E6%98%AF%E4%BB%80%E4%B9%88%EF%BC%9F"><span class="nav-text">聚簇索引和非聚簇索引是什么？</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#%E4%B8%BB%E9%94%AE%E7%B4%A2%E5%BC%95%E5%92%8C%E9%9D%9E%E4%B8%BB%E9%94%AE%E7%B4%A2%E5%BC%95%E6%9C%89%E4%BB%80%E4%B9%88%E5%8C%BA%E5%88%AB%EF%BC%9F"><span class="nav-text">主键索引和非主键索引有什么区别？</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#B-Tree-%E5%92%8C-B-Tree-%E7%9A%84%E7%AE%80%E5%8D%95%E7%90%86%E8%A7%A3"><span class="nav-text">B-Tree 和 B+Tree 的简单理解</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#%E5%A6%82%E4%BD%95%E9%81%BF%E5%85%8D%E5%9B%9E%E8%A1%A8%EF%BC%9F"><span class="nav-text">如何避免回表？</span></a></li></ol></div>
        </div>
        <!--/noindex-->

        <div class="site-overview-wrap sidebar-panel">
          <div class="site-author site-overview-item animated" itemprop="author" itemscope itemtype="http://schema.org/Person">
  <p class="site-author-name" itemprop="name">一年春又来</p>
  <div class="site-description" itemprop="description"></div>
</div>
<div class="site-state-wrap site-overview-item animated">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
          <a href="/archives/">
        
          <span class="site-state-item-count">234</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
            <a href="/categories/">
          
        <span class="site-state-item-count">38</span>
        <span class="site-state-item-name">分类</span></a>
      </div>
      <div class="site-state-item site-state-tags">
            <a href="/tags/">
          
        <span class="site-state-item-count">125</span>
        <span class="site-state-item-name">标签</span></a>
      </div>
  </nav>
</div>



        </div>
      </div>
    </div>
  </aside>
  <div class="sidebar-dimmer"></div>


    </header>

    
  <div class="back-to-top" role="button">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>

<noscript>
  <div class="noscript-warning">Theme NexT works best with JavaScript enabled</div>
</noscript>


    <div class="main-inner post posts-expand">


  


<div class="post-block">
  
  

  <article itemscope itemtype="http://schema.org/Article" class="post-content" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="http://littlefxc.github.io/2022/03/18/docs/MySQL/%E4%BB%80%E4%B9%88%E6%98%AFMySQL%E7%9A%84%E5%9B%9E%E8%A1%A8/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/images/avatar.gif">
      <meta itemprop="name" content="一年春又来">
      <meta itemprop="description" content="">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="一年春又来">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          什么是MySQL的回表?
        </h1>

        <div class="post-meta-container">
          <div class="post-meta">
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-calendar"></i>
      </span>
      <span class="post-meta-item-text">发表于</span>

      <time title="创建时间：2022-03-18 02:41:19" itemprop="dateCreated datePublished" datetime="2022-03-18T02:41:19+08:00">2022-03-18</time>
    </span>
      <span class="post-meta-item">
        <span class="post-meta-item-icon">
          <i class="far fa-calendar-check"></i>
        </span>
        <span class="post-meta-item-text">更新于</span>
        <time title="修改时间：2022-05-10 09:23:09" itemprop="dateModified" datetime="2022-05-10T09:23:09+08:00">2022-05-10</time>
      </span>
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-folder"></i>
      </span>
      <span class="post-meta-item-text">分类于</span>
        <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
          <a href="/categories/%E6%95%B0%E6%8D%AE%E5%BA%93/" itemprop="url" rel="index"><span itemprop="name">数据库</span></a>
        </span>
    </span>

  
</div>

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">
        <p>[toc]</p>
<h1 id="引言"><a href="#引言" class="headerlink" title="引言"></a>引言</h1><p>简单来说，回表就是 MySQL 要先查询到主键索引，然后再用主键索引定位到数据。</p>
<p>下面，对一些问题进行分析与回答：</p>
<ul>
<li>什么是聚簇索引？什么是非聚簇索引？</li>
<li>为什么回表要先查到主键索引？</li>
<li>主键索引和非主键索引有什么区别？</li>
<li>如何避免回表？</li>
</ul>
<h1 id="聚簇索引和非聚簇索引是什么？"><a href="#聚簇索引和非聚簇索引是什么？" class="headerlink" title="聚簇索引和非聚簇索引是什么？"></a>聚簇索引和非聚簇索引是什么？</h1><p>MySQL 的索引有不同的角度的分类方式，例如：按数据结构分、按逻辑角度分、按物理存储分。</p>
<p>其中，按物理存储分有两种索引：<strong>聚簇索引</strong>和<strong>非聚簇索引</strong>。</p>
<p>简单来说，<strong>聚簇索引是主键索引</strong>。</p>
<p><strong>主键索引之外的就是非聚簇索引</strong>，非聚簇索引又叫辅助索引或者二级索引。</p>
<h1 id="主键索引和非主键索引有什么区别？"><a href="#主键索引和非主键索引有什么区别？" class="headerlink" title="主键索引和非主键索引有什么区别？"></a>主键索引和非主键索引有什么区别？</h1><p>相同点：都使用的是 B+Tree 。</p>
<p>不同点：叶子节点存储的数据不同</p>
<ul>
<li>主键索引的叶子节点存储的是<strong>一行完整的数据</strong>；</li>
<li>非主键索引的叶子节点存储的是<strong>主键值</strong>。叶子节点不包含记录的全部数据，非主键的叶子节点除了用来排序的 key 还包含一个书签（bookmark），其中存储了聚簇索引的 key。</li>
</ul>
<p>那么这两种索引在使用方面上有什么区别呢？</p>
<ol>
<li>使用主键索引查询 <figure class="highlight sql"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"># 主键索引的的叶子节点存储的是<span class="operator">*</span><span class="operator">*</span>一行完整的数据<span class="operator">*</span><span class="operator">*</span>，</span><br><span class="line"># 所以只需搜索主键索引的 B<span class="operator">+</span>Tree 就可以轻松找到全部数据</span><br><span class="line"><span class="keyword">select</span> <span class="operator">*</span> <span class="keyword">from</span> <span class="keyword">user</span> <span class="keyword">where</span> id <span class="operator">=</span> <span class="number">1</span>;</span><br></pre></td></tr></table></figure>
</li>
<li>使用非主键索引查询 <figure class="highlight sql"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"># 非主键索引的叶子节点存储的是<span class="operator">*</span><span class="operator">*</span>主键值<span class="operator">*</span><span class="operator">*</span>，</span><br><span class="line"># 所以MySQL会先查询到 name 列的索引的 B<span class="operator">+</span>Tree，搜索得到对应的主键值</span><br><span class="line"># 然后再去搜索该主键值查询主键索引的 B<span class="operator">+</span>Tree 才可以找到对应的数据</span><br><span class="line"><span class="keyword">select</span> <span class="operator">*</span> <span class="keyword">from</span> <span class="keyword">user</span> <span class="keyword">where</span> name <span class="operator">=</span> <span class="string">&#x27;Jack&#x27;</span>;</span><br></pre></td></tr></table></figure>
</li>
</ol>
<p>可以看出使用非主键索引要比主键索引多使用一次 B+Tree。</p>
<h2 id="B-Tree-和-B-Tree-的简单理解"><a href="#B-Tree-和-B-Tree-的简单理解" class="headerlink" title="B-Tree 和 B+Tree 的简单理解"></a>B-Tree 和 B+Tree 的简单理解</h2><p>理解聚簇索引和非聚簇索引的关键在于 B+Tree 的理解。</p>
<p>用一幅图来表示，其它的就不再过多解释了：</p>
<p><img src="https://gitee.com/littlefxc/oss/raw/master/images/8ec43769f81ea5e901077f047b8da974.png" alt="https://gitee.com/littlefxc/oss/raw/master/images/KjXSSU.jpg"></p>
<p>这里只是简单介绍一下 B-Tree 和 B+Tree 的区别：</p>
<ol>
<li>B+树中只有叶子节点会带有指向记录的指针，而B树则所有节点都带有，在内部节点出现的索引项不会再出现在叶子节点中。</li>
<li>B+树中所有叶子节点都是通过指针连接在一起，而B树不会。</li>
</ol>
<h1 id="如何避免回表？"><a href="#如何避免回表？" class="headerlink" title="如何避免回表？"></a>如何避免回表？</h1><p>使用覆盖索引，<strong>所谓覆盖索引就是指索引中包含了查询中的所有字段，这种情况下就不需要再进行回表查询了。</strong></p>

    </div>

    
    
    

    <footer class="post-footer">
          <div class="post-tags">
              <a href="/tags/mysql/" rel="tag"># mysql</a>
          </div>

        

          <div class="post-nav">
            <div class="post-nav-item">
                <a href="/2022/03/16/docs/JVM/JVM-JDK8%E7%9A%84JVM%E5%8F%82%E6%95%B0/" rel="prev" title="JVM JDK8的JVM参数">
                  <i class="fa fa-chevron-left"></i> JVM JDK8的JVM参数
                </a>
            </div>
            <div class="post-nav-item">
                <a href="/2022/03/18/docs/%E5%BE%AE%E6%9C%8D%E5%8A%A1/Redis/" rel="next" title="Redis">
                  Redis <i class="fa fa-chevron-right"></i>
                </a>
            </div>
          </div>
    </footer>
  </article>
</div>







<script>
  window.addEventListener('tabs:register', () => {
    let { activeClass } = CONFIG.comments;
    if (CONFIG.comments.storage) {
      activeClass = localStorage.getItem('comments_active') || activeClass;
    }
    if (activeClass) {
      const activeTab = document.querySelector(`a[href="#comment-${activeClass}"]`);
      if (activeTab) {
        activeTab.click();
      }
    }
  });
  if (CONFIG.comments.storage) {
    window.addEventListener('tabs:click', event => {
      if (!event.target.matches('.tabs-comment .tab-content .tab-pane')) return;
      const commentClass = event.target.classList[1];
      localStorage.setItem('comments_active', commentClass);
    });
  }
</script>
</div>
  </main>

  <footer class="footer">
    <div class="footer-inner">


<div class="copyright">
  &copy; 
  <span itemprop="copyrightYear">2022</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">一年春又来</span>
</div>
  <div class="powered-by">由 <a href="https://hexo.io/" class="theme-link" rel="noopener" target="_blank">Hexo</a> & <a href="https://theme-next.js.org/mist/" class="theme-link" rel="noopener" target="_blank">NexT.Mist</a> 强力驱动
  </div>

    </div>
  </footer>

  
  <script src="https://cdn.jsdelivr.net/npm/animejs@3.2.1/lib/anime.min.js"></script>
<script src="/js/utils.js"></script><script src="/js/motion.js"></script><script src="/js/schemes/muse.js"></script><script src="/js/next-boot.js"></script>

  
<script src="/js/local-search.js"></script>






  





</body>
</html>
